import datetime

# Create your views here.
from django.db.models import Count
from django.utils import timezone

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAdminUser
from datetime import date

from .serializers import GoodsSerialrizer
from users.models import User
from orders.models import OrderInfo

now_date = date.today()
print('当前日期：',now_date)
# 用户总数
class UserTotalCountView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):

        # 当前时刻
        cur_time = timezone.localtime() # 当前时间 2021-01-08 02:19:35.122692+00:00
        print('当前时间：',cur_time)

        # 获取所有用户总数
        count = User.objects.count()

        return Response({
            'count': count,
            # 'date': now_date,
            'date': cur_time.date(),  # 把datetime对象转化为date对象（只保留年月日）
        })


# 日增用户统计
class UserDayCountView(APIView):
    permission_classes = [IsAdminUser]


    def get(self, request):
        # 获取当日零时刻
        cur_time = timezone.localtime()
        cur_0_time = cur_time.replace(hour=0, minute=0, second=0)  # 把时分秒全部替换成0，得到当天的0时刻
        print('当天零时刻：', cur_0_time)

        # 获取新增用户数量
        count = User.objects.filter(date_joined__gte=now_date).count()
        # count = User.objects.filter(date_joined__gte=cur_0_time).count()

        return Response({
            'count': count,
            'date': now_date,
            # 'date': cur_0_time.date(),
        })


# 日活跃用户统计
class UserActiveCountView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):

        # 获取今日活跃用户数量
        count = User.objects.filter(last_login__gte=now_date).count()

        return Response({
            'count': count,
            'date': now_date,
        })


# 日下单用户统计
class UserOrderCountView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):

        # 获取今日下单用户数量
        # orders = OrderInfo.objects.filter(create_time__gte=now_date)
        # count = orders.count()
        #
        # user_set = set()
        # for order in orders:
        #     user = order.user # 当前订单关联用户
        #     user_set.add(user) # 集合插入自动去重
        # count = len(user_set)


        # values('分组字段').annotate(别名=聚合函数('字段'))
        orders = OrderInfo.objects.filter(create_time__gte=now_date)
        count = orders.values('user_id').annotate(count=Count('user_id')).count()
        return Response({
            'count': count,
            'date': now_date,
        })


# 月增用户统计
class UserMonthCountView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):

        # 一个月之前的今天
        start_date = now_date - datetime.timedelta(29)
        # 创建空列表保存保存每天的用户量
        data_list = []

        # 循环遍历每天用户量
        for i in range(30):
            # 当前日期
            index_date = start_date + datetime.timedelta(days=i)
            # 后一天的日期
            next_date = index_date + datetime.timedelta(days=i + 1)

            count = User.objects.filter(date_joined__gte=index_date, date_joined__lt=next_date).count()
            data_list.append({
                'count': count,
                'date': index_date
            })

        return Response(data_list)


# 日分类商品用户量
from goods.models import GoodsVisitCount


class GoodsDayView(APIView):
    def get(self, request):

        # 获取当天访问商品的分类数量
        data = GoodsVisitCount.objects.filter(date=now_date)
        # 序列化分类数量
        ser = GoodsSerialrizer(data, many=True)

        return Response(ser.data)



